package com.efesco.system;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bstek.dorado.action.Action;
import com.bstek.dorado.action.impl.AbstractAccessController;
import com.bstek.dorado.utils.*;
import com.bstek.dorado.common.ds.ConnectionHelper;

/**
 * Login
 */
public class Login extends AbstractAccessController {
  public boolean login(Action action, HttpServletRequest request,
                       HttpServletResponse httpServletResponse) {
    String username = request.getParameter("userName");
    String password = request.getParameter("password");
    User user=null;
    try{
       user=checkUser(username,password);
    }catch(Exception e){
    }finally{
    } 
    //System.out.println(action.getController().getName()+"444444");
    if (user==null){
    	action.addMessage("adfadfasdf");
    	return false;
    }    	
    request.getSession().setAttribute("User",user);
    return true;   
  }

  public void logout(Action action, HttpServletRequest request,
                     HttpServletResponse httpServletResponse) {
  }
  
  private User checkUser(String userName,String passwd)throws Exception{
	  String sql="select user_id,employee_id,single_company_id,"
	      +"foreign_enterprise_id,role_type,for_employee_id,real_name from s_user where "
	      +"user_name='"+userName+"' and password='"+passwd+"'";
	  Connection connection=null;
	  User user=null;
	  try{
		  connection = ConnectionHelper.getConnection(null);
		  Statement st = connection.createStatement();
		  ResultSet rs = st.executeQuery(sql);
		  if(rs.next()){
			  int userId=rs.getInt(1);
			  String empId=rs.getString(2);
			  String comId=rs.getString(3);
			  String fornId=rs.getString(4);
			  String forEmpId=rs.getString(6);
			  int role=rs.getInt(5);
			  String realName=rs.getString(7);
			  user=new User(userId,userName,empId,comId,fornId,forEmpId,role,realName);	
		  }
		  rs.close();
		  st.close();
	  }finally{
		  connection.close();
	  }
	  return user;
  }

}
